package my.edu.security.shiroservice;

import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import my.edu.model.User.entity.SystemConfig;
import my.edu.common.utils.JsonUtils;
import my.edu.common.utils.RedisUtils;
import my.edu.model.User.service.*;
import my.edu.security.userEntity.UserDetail;
import my.edu.security.userEntity.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;


@Component
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    IPermissionService permissionService;
    @Autowired
    ISystemConfigService systemConfigService;
    @Resource
    IUserService userService;
    @Autowired
    IRolePermissionService rolePermissionService;
    @Autowired
    private IRoleService roleService;

    @Override
    public Set<String> getUserPermissions(UserDetail user) {
        Object cachePermissionSet = redisUtils.hMGetAll("permissionSet").get("user_" + user.getUsername());
        if (!(cachePermissionSet instanceof Set)){
            //系统管理员，拥有最高权限
            List<String> permissionsList;
            if (user.getUsername().equals("admin")) {
                permissionsList =new ArrayList<>(permissionService.getAllUrl()) ;
            } else {
                permissionsList = new ArrayList<>(permissionService.getUrlByUserId(user.getId()));
            }

            //用户权限列表
            Set<String> permsSet = new HashSet<>();
            for (String permissions : permissionsList) {
                if (StrUtil.isBlank(permissions)) {
                    continue;
                }
                permsSet.addAll(Arrays.asList(permissions.trim().split(",")));
            }
            redisUtils.hSet("permissionSet","user_" + user.getUsername(),permsSet);
            return permsSet;
        }else {
            return (Set<String>)cachePermissionSet;
        }
    }

    @Override
    public UserToken getToken(Long userId) {
        UserToken token1 = JsonUtils.parseObject(redisUtils.hMGet("loginUser", userId + ""),UserToken.class);
        return token1;
    }

    @Override
    public Set<String> getUserRoles(UserDetail user) {
        Object cacheRoleSet = redisUtils.hMGetAll("roleSet").get("user_" + user.getUsername());
        if (cacheRoleSet == null || !(cacheRoleSet instanceof Set)){
            List<String>  roles= roleService.getRoleNameByUserId(user.getId());
            HashSet<String> roleSet = new HashSet<>(roles);
            redisUtils.hSet("roleSet","user_" + user.getUsername(),roleSet);
            return roleSet;
        }else {
            return (Set<String>)cacheRoleSet;
        }
    }
}